import { useState } from 'react'
import { invoke } from '@tauri-apps/api/tauri'
import './App.css'

interface Product {
  id : string
  url : string
  status: boolean
  images: Image
}
interface Image {
  main_src: []
  detail_src: []
  comment_src: []
}

function App() {
  const [greetMsg, setGreetMsg] = useState('')
  const [websiteValue, setWebSiteValue] = useState('')
  const [dirValue, setDirValue] = useState('')
  const [images, setImages] = useState<Image>()
  const [products, setProducts] = useState<Product[]>()
  const [loading, setLoading] = useState(false)

  // 处理点击单元格事件
  const handleCellClick = (productId: string) => {
    const index = products?.findIndex(image => image.id === productId);
    if (index !== undefined && index !== -1 && products && products[index]) {
        setImages(products[index].images)
    }
  };

  async function greet() {
    setLoading(true)
    setProducts([])
    const websites = websiteValue.split('\n')
    for (const website of websites) {
      const productId= website.match(/(\d+)(\?|$)/)?.[0]
      setProducts((prevProducts: Product[] | undefined) => {
        const newProductId: string = productId || ''; // 使用默认值或者添加逻辑来确保 productId 是一个字符串
        const newProduct: Product = {
          id: newProductId,
          url: website,
          status: false,
          images: {
            main_src: [],
            detail_src: [],
            comment_src: []
          }
        };
        return [
          ...(prevProducts || []),
          newProduct
        ];
      });

      console.log(products)

      await invoke('greet', {
        website: website,
        dirValue: dirValue
      })
        .then(message => {
          const processedElements = JSON.parse(message as string)
          // 更新对应的产品对象
          setProducts(prevProducts => {
            if (!prevProducts) return prevProducts; // 如果 prevProducts 是 undefined，则不做任何更新
            return prevProducts.map(product => {
              if (product.id === productId) {
                return {
                  ...product,
                  status: true,
                  images: processedElements
                };
              }
              return product;
            });
          })}).catch(error => setGreetMsg(String(error)))
    }
    setLoading(false)
  }

  return (
    <>
      <div className="container">
        <h1>Welcome to Kee!</h1>
        <div className="row">
          <a href="javascript:" target="_blank">
            <img
              src="/6D413FCBAA8A9B7D0CF1F2648CA249BF.jpg"
              className="logo vite"
              alt="Vite logo"
            />
          </a>
          <a href="javascript:" target="_blank">
            <img
              src="/6D413FCBAA8A9B7D0CF1F2648CA249BF.jpg"
              className="logo tauri"
              alt="Tauri logo"
            />
          </a>
          <a href="javascript:" target="_blank">
            <img
              src="/6D413FCBAA8A9B7D0CF1F2648CA249BF.jpg"
              className="logo react"
              alt="React logo"
            />
          </a>
        </div>

        <h4>请输入站点地址以及下载目录爬取</h4>

        <form
          onSubmit={e => {
            e.preventDefault()
            setGreetMsg('')
            setImages(undefined)
            greet()
          }}
        >
          <div className="row" style={{ marginBottom: '10px' }}>
            <input
              value={dirValue}
              id="greet-input"
              onChange={e => setDirValue(e.currentTarget.value)}
              placeholder="下载目录"
            />
          </div>
          <div className="row" style={{ marginBottom: '10px' }}>
            <textarea
              value={websiteValue}
              id="greet-textarea"
              onChange={e => setWebSiteValue(e.currentTarget.value)}
              placeholder="网址（每行一个）"
              rows={5}
              cols={50}
            />
          </div>
          <div className="row" style={{ marginBottom: '10px' }}>
            <button type="submit" disabled={loading}>
              {loading ? <div className="spinner"></div> : '爬取'}
            </button>
          </div>
        </form>

        {products && products.length > 0 && (
          <div className="row">
            <table>
              <thead>
              <tr>
                <th>网址</th>
                <th>产品标识</th>
                <th>爬取状态</th>
                <th>操作</th>
              </tr>
              </thead>
              <tbody>
              {products.map(item => (
                <tr key={item.id}>
                  <td>{item.url}</td>
                  <td>{item.id}</td>
                  <td>{item.status ? '完成' : '爬取中'}</td>
                  <td>
                    <button type="button" onClick={() => handleCellClick(item.id)}>
                      详情
                    </button>
                  </td>
                </tr>
              ))}
              </tbody>
            </table>
          </div>

        )}
        {greetMsg.length > 0 && <p>{greetMsg}</p>}
        {images && images.main_src && images.main_src.length > 0 && (
          <h4>主图</h4>
        )}
        <div className="image_container">
          {images &&
            images.main_src.map((image, index) => (
              <img
                key={index}
                src={image}
                alt={`Image ${index}`}
                style={{
                  width: '200px',
                  height: '200px',
                  marginBottom: '10px',
                  margin: '5px'
                }}
              />
            ))}
        </div>
        {images && images.detail_src && images.detail_src.length > 0 && (
          <h4>详情图</h4>
        )}
        <div className="image_container">
          {images &&
            images.detail_src.map((image, index) => (
              <img
                key={index}
                src={image}
                alt={`Image ${index}`}
                style={{
                  width: '200px',
                  height: '200px',
                  marginBottom: '10px',
                  margin: '5px'
                }}
              />
            ))}
        </div>
        {images && images.comment_src && images.comment_src.length > 0 && (
          <h4>评论图</h4>
        )}
        <div className="image_container">
          {images &&
            images.comment_src.map((image, index) => (
              <img
                key={index}
                src={image}
                alt={`Image ${index}`}
                style={{
                  width: '200px',
                  height: '200px',
                  marginBottom: '10px',
                  margin: '5px'
                }}
              />
            ))}
        </div>
      </div>
    </>
  )
}

export default App
